package com.huluobo.a2203kotlindouyindemo.live

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlindouyindemo.R
import com.huluobo.a2203kotlindouyindemo.adapter.GiftAdapter
import com.huluobo.a2203kotlindouyindemo.adapter.MessageAdapter
import com.huluobo.a2203kotlindouyindemo.databinding.ActivityLiveBinding
import com.huluobo.a2203kotlindouyindemo.shop.ShopActivity
import com.huluobo.a2203kotlindouyindemo.utils.ImageUtils
import com.huluobo.base.bean.GiftBean
import com.huluobo.base.bean.MessageEntity
import com.huluobo.base.bean.Money
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity
import com.huluobo.base.view.BaseMVVMFragment
import com.hyphenate.EMCallBack
import com.hyphenate.EMChatRoomChangeListener
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

class LiveActivity : BaseMVVMActivity<ActivityLiveBinding, LiveViewModel>() {
    private lateinit var videoBean: VideoBean
    private lateinit var giftAdapter: GiftAdapter
    private val giftList = mutableListOf<GiftBean>()
    private lateinit var money: Money
    private lateinit var messageAdapter: MessageAdapter
    private val messageList = mutableListOf<MessageEntity>()

    //选中的礼物
    private lateinit var giftBean: GiftBean
    override fun initData() {
        viewModel.queryUserMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME))

        viewModel.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                dataBinding.liveFollowBtn.text = "已关注"
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
                videoBean.guanzhu = 1
            }
        }

        viewModel.followAuthFailed.observe(this) {
            Log.i("TagA", "关注失败:$it")
        }

        viewModel.noFollowAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                dataBinding.liveFollowBtn.text = "关注"
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
                videoBean.guanzhu = 0
            }
        }

        viewModel.noFollowAuthFailed.observe(this) {
            Log.i("TagA", "取消关注失败:$it")
        }

        viewModel.getGiftListSuccess.observe(this) {
            if (it.code == 200) {
                giftList.clear()
                giftList.addAll(it.data)
                giftAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getGiftListFailed.observe(this) {
            Log.i("TagA", "加载礼物列表失败:$it")
        }

        viewModel.queryUserMoneySuccess.observe(this) {
            money = it
            dataBinding.liveUserMoneyTv.text = "余额:${money.money}抖币"
        }

        viewModel.queryUserMoneyFailed.observe(this) {
            Log.i("TagA", "查询用户余额失败:$it")
        }
    }

    override fun initView() {
        videoBean = intent.getSerializableExtra("videoBean") as VideoBean

        dataBinding.liveGsyPlayer.backButton.visibility = View.GONE
        dataBinding.liveGsyPlayer.setUp(videoBean.videopath, true, "")
//        dataBinding.liveGsyPlayer.startPlayLogic()

        //头像
        ImageUtils.loadCircleImage(this, videoBean.headpath, dataBinding.liveUserIconIv)
        //作者
        dataBinding.liveUsernameTv.text = videoBean.authname
        //关注状态
        dataBinding.liveFollowBtn.text = if (videoBean.guanzhu == 0) "关注" else "已关注"
        dataBinding.liveFollowBtn.setBackgroundResource(if (videoBean.guanzhu == 0) R.drawable.shape_red else R.drawable.shape_alpha_black)
        //喜欢数量
        dataBinding.liveLikeCountTv.text = "${videoBean.like_count}人喜欢"
        //关注状态的点击事件
        dataBinding.liveFollowBtn.setOnClickListener {
            if (videoBean.guanzhu == 0) {
                //触发关注接口
                viewModel.followAuth(videoBean.authname)
            } else {
                //触发取消关注接口
                viewModel.noFollowAuth(videoBean.authname)
            }
        }

        dataBinding.liveLikeView.addLikeImages(
            R.drawable.ic_favorite_0,
            R.drawable.ic_favorite_1,
            R.drawable.ic_favorite_2,
            R.drawable.ic_favorite_3,
            R.drawable.ic_favorite_4,
            R.drawable.ic_favorite_5,
            R.drawable.ic_favorite_4,
            R.drawable.ic_favorite_3,
            R.drawable.ic_favorite_2,
            R.drawable.ic_favorite_1,
            R.drawable.ic_favorite_0
        )

        dataBinding.liveLikeIv.setOnClickListener {
            dataBinding.liveLikeView.addFavor()
        }

        dataBinding.liveDanmuIv.setOnClickListener {
            dataBinding.liveDanmuInputLl.visibility = View.VISIBLE
        }

        initDanmuView()

        dataBinding.liveDanmuSendIv.setOnClickListener {
            sendDanmu()
        }

        //初始化礼物列表
        dataBinding.liveGiftRv.layoutManager = GridLayoutManager(this, 5)
        giftAdapter = GiftAdapter(giftList)
        dataBinding.liveGiftRv.adapter = giftAdapter

        //礼物列表点击事件
        giftAdapter.setOnItemClickListener { adapter, view, position ->
            giftBean = giftList[position]
            ImageUtils.loadImage(this, giftBean.giftpath, dataBinding.liveGiftSelectIv)
            dataBinding.liveGiftSelectTv.text = giftBean.giftname
        }

        //礼物发送的点击事件
        dataBinding.liveGiftSendBtn.setOnClickListener {
            sendGift()
        }

        dataBinding.liveGiftIv.setOnClickListener {
            dataBinding.liveGiftCl.visibility = View.VISIBLE
            viewModel.getGiftList()
        }

        dataBinding.liveCloseTv.setOnClickListener {
            dataBinding.liveGiftCl.visibility = View.GONE
        }

        dataBinding.livePayBtn.setOnClickListener {
            money.money += 5000f
            viewModel.updateUserMoney(money)
        }

        //初始化聊天列表
        messageAdapter = MessageAdapter(messageList)
        dataBinding.liveChatRoomRv.layoutManager = LinearLayoutManager(this)
        dataBinding.liveChatRoomRv.adapter = messageAdapter

        dataBinding.liveChatRoomSendIv.setOnClickListener {

            val emMessage = EMMessage.createTextSendMessage(
                dataBinding.liveChatRoomInputEt.text.toString(),
                Const.CHAT_ROOM_ID
            )
            emMessage.chatType = EMMessage.ChatType.ChatRoom
            emMessage.body = EMTextMessageBody(dataBinding.liveChatRoomInputEt.text.toString())
            EMClient.getInstance().chatManager().sendMessage(emMessage)

            emMessage.setMessageStatusCallback(object : EMCallBack {
                override fun onSuccess() {
                    runOnUiThread {
                        //发送消息成功
                        val messageEntity = MessageEntity(
                            EMClient.getInstance().currentUser,
                            dataBinding.liveChatRoomInputEt.text.toString()
                        )
                        messageList.add(messageEntity)
                        messageAdapter.notifyDataSetChanged()
                        dataBinding.liveChatRoomRv.scrollToPosition(messageList.size - 1)
                        dataBinding.liveChatRoomInputEt.text.clear()
                        dataBinding.liveChatRoomInputLl.visibility = View.GONE
                    }
                }

                override fun onError(code: Int, error: String?) {
                    //发送消息失败
                }
            })
        }

        //初始化聊天室
        initChatRoom()

        dataBinding.liveInputTv.setOnClickListener {
            dataBinding.liveChatRoomInputLl.visibility = View.VISIBLE
        }

        dataBinding.liveCartIv.setOnClickListener {
            val intent = Intent(this, ShopActivity::class.java)
            startActivity(intent)
        }

    }

    private fun initChatRoom() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener)
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, object : EMValueCallBack<EMChatRoom> {
            override fun onSuccess(value: EMChatRoom?) {
                Log.i("TagA", "加入聊天室成功")
            }

            override fun onError(error: Int, errorMsg: String?) {
                Log.i("TagA", "加入聊天室失败:$error,$errorMsg")
            }
        })
    }

    private val messageListener = EMMessageListener {
        runOnUiThread {
            it.forEach {
                val messageEntity = MessageEntity(
                    it.userName,
                    (it.body as EMTextMessageBody).message
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID)
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener)
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
    }

    private val chatRoomChangeListener = object : EMChatRoomChangeListener {
        override fun onChatRoomDestroyed(roomId: String?, roomName: String?) {
        }

        override fun onMemberJoined(roomId: String?, participant: String?) {
            runOnUiThread {
                val messageEntity = MessageEntity(
                    "系统",
                    "${participant}进入直播间"
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onMemberExited(roomId: String?, roomName: String?, participant: String?) {
            runOnUiThread {
                val messageEntity = MessageEntity(
                    "系统",
                    "${participant}退出直播间"
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onRemovedFromChatRoom(reason: Int, roomId: String?, roomName: String?, participant: String?) {
        }

        override fun onMuteListAdded(chatRoomId: String?, mutes: MutableList<String>?, expireTime: Long) {
        }

        override fun onMuteListRemoved(chatRoomId: String?, mutes: MutableList<String>?) {
        }

        override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {
        }

        override fun onAdminAdded(chatRoomId: String?, admin: String?) {
        }

        override fun onAdminRemoved(chatRoomId: String?, admin: String?) {
        }

        override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {
        }

        override fun onAnnouncementChanged(chatRoomId: String?, announcement: String?) {
        }

    }

    //发送礼物
    private fun sendGift() {
        //判断用户余额是否充足
        if (money.money < giftBean.price) {
            ToastUtils.showLong("用户余额不足,请充值")
            return
        }

        val newMoney = money.money - giftBean.price
        dataBinding.liveUserMoneyTv.text = "余额:${newMoney}抖币"

        money.money = newMoney
        viewModel.updateUserMoney(money)


        val giftAnimView = ImageView(this)//创建一个view用于展示礼物
        //一个View无法直接赋值宽高,需要拿到LayoutParams
        val params = ConstraintLayout.LayoutParams(200, 200)//px
        giftAnimView.layoutParams = params

        dataBinding.liveRootCl.addView(giftAnimView)//把创建的ImageView添加到布局上
        ImageUtils.loadImage(this, giftBean.giftpath, giftAnimView)//给imageView赋值

        //拿到Layout的宽高
        val width = dataBinding.liveRootCl.measuredWidth
        val height = dataBinding.liveRootCl.measuredHeight

        val translationY =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationY",
                height.toFloat(),
                (height / 3).toFloat(),
                (height / 2).toFloat()
            )

        val translationX =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationX",
                (width / 2).toFloat(),
                (width / 3).toFloat(),
                (width / 2).toFloat(),
                (width / 3).toFloat()
            )

        val rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 0.1f, 0.5f, 1f, 0.5f, 0.1f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha)
        animatorSet.addListener(object : AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                dataBinding.liveGiftCl.visibility = View.GONE
            }

            override fun onAnimationEnd(animation: Animator) {
                dataBinding.liveRootCl.removeView(giftAnimView)
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }
        })
        animatorSet.start()

    }

    //发送弹幕
    private fun sendDanmu() {
        //获取弹幕的内容
        val danmuString = dataBinding.liveDanmuInputEt.text.toString()
        if (danmuString.isEmpty()) {
            ToastUtils.showLong("弹幕内容不能为空")
            return
        }

        //清理弹幕
        dataBinding.liveDanmuView.clear()
        dataBinding.liveDanmuView.removeAllLiveDanmakus()

        //构建一个弹幕的对象
        val danmuku = danmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        danmuku.text = danmuString
        danmuku.textSize = 30f
        danmuku.textColor = Color.WHITE
        danmuku.padding = 10
        danmuku.time = 800

        //弹幕添加到view中
        dataBinding.liveDanmuView.addDanmaku(danmuku)
        dataBinding.liveDanmuView.start()

        //发送完毕之后,清空弹幕输入框,隐藏布局
        dataBinding.liveDanmuInputEt.postDelayed({
            dataBinding.liveDanmuInputEt.text.clear()
            dataBinding.liveDanmuInputLl.visibility = View.GONE
        }, 300)
    }

    //弹幕的上下文
    private lateinit var danmuContext: DanmakuContext

    //初始化弹幕
    private fun initDanmuView() {
        //1.清空弹幕缓存
        dataBinding.liveDanmuView.enableDanmakuDrawingCache(false)
        dataBinding.liveDanmuView.clear()
        dataBinding.liveDanmuView.removeAllLiveDanmakus()

        //2.创建弹幕上下文
        danmuContext = DanmakuContext.create()

        //3.准备弹幕
        dataBinding.liveDanmuView.prepare(object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }, danmuContext)
    }

    override fun getViewModel(): Class<LiveViewModel> {
        return LiveViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_live
}